package com.tanhua.server.service;



import com.tanhua.domain.mongo.RecommendUser;
import com.tanhua.domain.vo.TodayBest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;

//@Service
public class RecommendUserService {

    @Autowired
    private MongoTemplate mongoTemplate;


    public TodayBest queryTodayBest(Long userId) {
        // 条件
        Criteria criteria = Criteria.where("toUserId").is(userId);
        // 按照得分倒序排序，获取第一条数据
        Query query = Query.query(criteria).with(Sort.by(Sort.Order.desc("score")))
                .limit(1);

        RecommendUser user = this.mongoTemplate.findOne(query, RecommendUser.class);

        TodayBest todayBest = new TodayBest();
        // 如果得分为98.2时，需要显示的得分是98
        double score = Math.floor(user.getScore());

        todayBest.setFateValue(Double.valueOf(score).longValue()); //缘分值

        todayBest.setId(user.getUserId()); //用户id

        return todayBest;
    }

    public List<RecommendUser>  queryRecommendUserList(Long userId, Integer page, Integer pagesize) {
        // 条件
        Criteria criteria = Criteria.where("toUserId").is(userId);
        Pageable pageable = PageRequest.of(page - 1, pagesize, Sort.by(Sort.Order.desc("score")));
        Query query = Query.query(criteria).with(pageable);
        return this.mongoTemplate.find(query, RecommendUser.class);
    }

    /**
     * 查询推荐好友的缘分值
     *
     * @param userId
     * @param toUserId
     * @return
     */
    double queryScore(Long userId, Long toUserId) {
        Query query = Query.query(Criteria
                .where("toUserId").is(toUserId)
                .and("userId").is(userId));
        RecommendUser recommendUser = this.mongoTemplate.findOne(query, RecommendUser.class);
        if (null == recommendUser) {
            return 0;
        }
        return recommendUser.getScore();
    }
}
